package com.ruyuan.commodity.builder;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruyuan.commodity.common.mamager.CategoryManager;
import com.ruyuan.commodity.elasticsearch.GoodsDocument;
import com.ruyuan.commodity.elasticsearch.GoodsParamIndex;
import com.ruyuan.commodity.model.goods.dos.CategoryDO;
import com.ruyuan.commodity.open.api.client.shop.api.ShopCatOpenApi;
import com.ruyuan.commodity.open.api.model.shop.dos.ShopCatDO;
import com.ruyuan.commodity.utils.HexUtils;
import com.ruyuan.commodity.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 商品ES文档类 构造器
 **/
@Component
public class GoodsDocumentBuilder {

    private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(GoodsDocumentBuilder.class);

    /**
     * 店铺商品分类的open api
     */
    @Autowired
    private ShopCatOpenApi shopCatOpenApi;
    /**
     * 商品类目业务管理器
     */
    @Autowired
    private CategoryManager categoryManager;
    /**
     * redis操作模板
     */
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 商品文档
     */
    private final GoodsDocument goodsDocument = new GoodsDocument();

    /**
     * 构建商品基础信息
     * @param goods 商品基础信息
     * @return 商品文档构造器
     */
    public GoodsDocumentBuilder buildGoodsBaseInfo(Map<String, Object> goods) {
        goodsDocument.setGoodsId(StringUtil.toLong(goods.get("goods_id").toString(), 0));
        goodsDocument.setGoodsName(goods.get("goods_name").toString());
        goodsDocument.setBrand(goods.get("brand_id") == null ? 0 :
                StringUtil.toLong(goods.get("brand_id").toString(), 0));
        goodsDocument.setCategoryId(goods.get("category_id") == null ? 0 :
                StringUtil.toLong(goods.get("category_id").toString(), 0));
        CategoryDO cat = categoryManager.getModel(Long.valueOf(goods.get("category_id").toString()));
        goodsDocument.setCategoryPath(cat.getCategoryPath() == null ? " "
                : HexUtils.encode(cat.getCategoryPath()));
        goodsDocument.setDisabled(StringUtil.toInt(goods.get("disabled").toString(), 0));
        goodsDocument.setMarketEnable(StringUtil.toInt(goods.get("market_enable").toString(), 0));
        goodsDocument.setIsAuth(StringUtil.toInt(goods.get("is_auth").toString(), 0));
        goodsDocument.setIntro(goods.get("intro") == null ? "" : goods.get("intro").toString());
        // 添加商品优先级维度
        goodsDocument.setPriority(goods.get("priority") == null ? 1
                : StringUtil.toInt(goods.get("priority").toString(), 1));

        return this;
    }

    /**
     * 构造商品价格类信息
     * @param goods 商品信息
     * @return 商品文档构造器
     */
    public GoodsDocumentBuilder buildGoodsPriceInfo(Map<String, Object> goods) {
        double goodsPrice = goods.get("price") == null ? 0D : StringUtil.toDouble(goods.get("price").toString(), 0D);
        goodsDocument.setPrice(goodsPrice);
        double discountPrice = goods.get("discount_price") == null ? 0d : StringUtil.toDouble(goods.get("discount_price").toString(), 0d);
        goodsDocument.setDiscountPrice(discountPrice);

        return this;
    }

    /**
     * 构造商品图片类信息
     * @param goods 商品信息
     * @return 商品文档构造器
     */
    public GoodsDocumentBuilder buildGoodsImgInfo(Map<String, Object> goods) {
        goodsDocument.setThumbnail(goods.get("thumbnail") == null ? "" : goods.get("thumbnail").toString());
        goodsDocument.setSmall(goods.get("small") == null ? "" : goods.get("small").toString());

        return this;
    }

    /**
     * 商品店铺类信息
     * @param goods 商品信息
     * @return 商品文档构造器
     */
    public GoodsDocumentBuilder buildShopInfo(Map<String, Object> goods) {
        goodsDocument.setSelfOperated(goods.get("self_operated") == null ? 0 :
                StringUtil.toInt(goods.get("self_operated").toString(), 0));
        goodsDocument.setSellerId(StringUtil.toLong(goods.get("seller_id").toString(), 0));
        goodsDocument.setSellerName(goods.get("seller_name").toString());
        // 店铺分组
        goodsDocument.setShopCatId(goods.get("shop_cat_id") == null ? 0 :
                StringUtil.toLong(goods.get("shop_cat_id").toString(), 0));
        goodsDocument.setShopCatPath("");

        Long shopCatId = goodsDocument.getShopCatId();
        LOG.info("shopCatId = {}", shopCatId);
        if (shopCatId != 0) {
            String key = "ShopCat_" + shopCatId;
            ShopCatDO shopCat = JSONUtil.toBean(redisTemplate.opsForValue().get(key), ShopCatDO.class);
            LOG.info("shopCat = {}", JSONUtil.toJsonStr(shopCat));
            if (ObjectUtils.isEmpty(shopCat.getShopCatId())) {
                shopCat = shopCatOpenApi.getModel(shopCatId);
                LOG.info("获取到的商品分类为 [{}]", JSONUtil.toJsonStr(shopCat));
                if (!ObjectUtils.isEmpty(shopCat)) {
                    redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopCat), 60L, TimeUnit.SECONDS);
                }
            }
            if (shopCat != null) {
                goodsDocument.setShopCatPath(HexUtils.encode(shopCat.getCatPath()));
            }
        }

        return this;
    }

    /**
     * 构建商品购物评论类信息
     * @param goods 商品信息
     * @return 商品文档构造器
     */
    public GoodsDocumentBuilder buildShoppingInfo(Map<String, Object> goods) {
        goodsDocument.setBuyCount(goods.get("buy_count") == null ? 0 :
                StringUtil.toInt(goods.get("buy_count").toString(), 0));
        goodsDocument.setCommentNum(goods.get("comment_num") == null ? 0 :
                StringUtil.toInt(goods.get("comment_num").toString(), 0));
        goodsDocument.setGrade(goods.get("grade") == null ? 100 :
                StringUtil.toDouble(goods.get("grade").toString(), 100d));

        return this;
    }

    /**
     * 构建商品属性类的信息
     * @param goods 商品信息
     * @return 商品文档构造器
     */
    public GoodsDocumentBuilder buildProperty(Map<String, Object> goods) {
        // 商品属性信息
        List<Map<String, String>> params = (List<Map<String, String>>) goods.get("params");
        List<GoodsParamIndex> paramsList = this.convertParam(params);
        goodsDocument.setParams(paramsList);

        return this;
    }

    /**
     * 创建商品文档
     * @return 构造好的商品文档
     */
    public GoodsDocument create() {
        return goodsDocument;
    }

    /**
     * 转换商品参数文档集合
     * @param params 商品参数信息
     * @return 商品参数信息的文档document对象
     */
    protected List<GoodsParamIndex> convertParam(List<Map<String, String>> params) {
        List<GoodsParamIndex> paramIndices = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(params)) {
            for (Map<String, String> param : params) {
                GoodsParamIndex index = new GoodsParamIndex();
                index.setName(StringUtils.isEmpty(param.get("param_name")) ? "" : param.get("param_name"));
                index.setValue(StringUtils.isEmpty(param.get("param_value")) ? "" : param.get("param_value"));
                paramIndices.add(index);
            }
        }
        return paramIndices;
    }

}
